import { Controller } from 'egg';
import { Op } from 'sequelize';

export default class GoodsAttrController extends Controller {



  // 商品属性列表
  async all() {
    const result = await this.ctx.service.goods.attr.model.findAll({
      include: [
        {
          model: this.ctx.model.AttrVal,
        }
      ],
    });

    if (result) {
      this.ctx.success({
        data: result
      });
    }
  }

  // 商品属性列表
  async list() {
    const { page, pageSize } = this.ctx.validateReq(
      'goods.attr.list',
    ).query;

    const where = {};
    const result = await this.ctx.service.goods.attr.index(page, pageSize, where);

    if (result) {
      this.ctx.success({
        data: result
      });
    }
  }


  // 新建商品属性
  async create() {
    const { body } = this.ctx.validateReq('goods.attr.create');

    const isExist = await this.ctx.model.AttrKey.findOne({
      where: {
        name: body.name,
      }
    });

    if (isExist) {
      return this.ctx.failure({
        code: 30000,
        data: {
          name: body.name,
        },
      });
    }

    const result = await this.ctx.service.goods.attr.create(body);

    if (result) {
      this.ctx.success({
        data: {
          id: result.id,
        },
        status: 201,
      });
    }
  }


  // 编辑商品属性
  async update() {

    const { body, params: { id } } = this.ctx.validateReq('goods.attr.update');

    const isExist = await this.ctx.model.AttrKey.findOne({
      where: {
        id: { [Op.ne]: id },
        name: body.name,
      }
    });

    if (isExist) {
      return this.ctx.failure({
        code: 30010,
        data: {
          name: body.name,
        },
      });
    }

    const result = await this.ctx.service.goods.attr.update(id, body);

    if (result) {
      this.ctx.success({
        data: {
          id: result.id,
        }
      });
    }
  }


  // 删除商品属性
  async destroy() {
    const { params: { id } } = this.ctx.validateReq('goods.attr.destroy');

    const result = await this.ctx.service.goods.attr.destroy(id);

    if (result) {
      this.ctx.success({
        data: {
          id: result.id,
        }
      });
    }
  }

  /**
   * 新增属性值
   */
  async val() {
    const { body, params: { id } } = this.ctx.validateReq('goods.attr.create.val');
    const { valList } = body;
    const list = valList.map((name: string) => {
      return {
        attr_key_id: id,
        name
      }
    });

    await this.ctx.model.AttrVal.destroy({
      where: {
        attr_key_id: id
      }
    });

    const result = await this.ctx.model.AttrVal.bulkCreate(list);

    if (result) {
      this.ctx.success({
        data: {
          id: result.id,
        }
      });
    }

  }

}
